from rest_framework.decorators import permission_classes
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from api.extension import return_code
from api.extension.mixins import OpsCreateModelMixin
from api.extension.auth import TokenAuthentication
from api.serializers.huaweicloud import CloudCdnSerializer
from api.extension.huaweicloud_cdn import HuaWeiCloudMiddleware
from api.models import HuaWeiCloud

class HuaWeiCloudCDNMiddleware(OpsCreateModelMixin, GenericViewSet):
    permission_classes = []
    authentication_classes = [TokenAuthentication,]
    serializer_class = CloudCdnSerializer
    throttle_objects = []

    def perform_create(self, serializer):
        urlspath = serializer.validated_data.get("urlspath")
        cloud_env = serializer.validated_data.get("cloud_env")
        cloud_object = HuaWeiCloud.objects.filter(id=cloud_env).first()
        ak = cloud_object.cloud_ak
        sk = cloud_object.cloud_sk
        region = "cn-north-1"
        cloud_obj = HuaWeiCloudMiddleware(ak, sk, region)
        client = cloud_obj.create_client()
        cloud_obj.refreshCache(urlspath, client)
        cloud_obj.preheatCache(urlspath, client)
        return Response({"code": return_code.SUCCESS, "data":"更新缓存成功"})
